package comunicacion;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import sistemaDefensivo.SistemaBateriaMisiles;

public class Servidor {

	private ServerSocket srvSocket;
	private Socket socket;
	
	private ObjectOutputStream writerObject;
	private ObjectInputStream readerObject;
	
	private DataOutputStream writerData;
	private DataInputStream readerData;
	
	private int puerto;
	private boolean hayConexion = false;
	
	public Servidor(int puerto){
		this.puerto = puerto;
	}
	
	public void abrirServidor(){
		try {
			srvSocket = new ServerSocket(puerto);
//			System.out.println("Servidor dice =====> Escuchando el puerto: " + srvSocket.getLocalPort());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void conectar(){
		try {
			socket = srvSocket.accept();
			writerObject = new ObjectOutputStream(socket.getOutputStream());
			readerObject = new ObjectInputStream(socket.getInputStream());
			writerData = new DataOutputStream(socket.getOutputStream());
			readerData = new DataInputStream(socket.getInputStream());			
			hayConexion = true;
//			System.out.println("Servidor dice =====> Se conecto el cliente: " + socket.getInetAddress());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void conectarMulti(SistemaBateriaMisiles sisBat){
		try {
			Socket socketTemp = new Socket();
			socketTemp = srvSocket.accept();
			ServerManager serverMgr = new ServerManager(socketTemp, sisBat);
			Thread hiloServerMgr = new Thread(serverMgr);
			hiloServerMgr.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendObject(Mensaje mensaje){
		try {
			writerObject.writeObject(mensaje);
			writerObject.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Mensaje readObject(){
		try {
			return (Mensaje) readerObject.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public int readDataInt(){
		try {
			return readerData.readInt();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -9;
		}
	}
	
	public void sendDataInt(int port){
		try {
			writerData.writeInt(port);
			writerData.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void closeSocket(){
		try {
			readerObject.close();
			writerObject.close();
			readerData.close();
			writerData.close();
			socket.close();
			hayConexion = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean hayConexion(){
		return hayConexion;
	}
	
	public int getPort(){
		return srvSocket.getLocalPort();
	}
}